/**
 * 跟随主角移动视角
 */
const {ccclass, property} = cc._decorator;

const MOVE_LENGTH = 48;

@ccclass
export default class Follow extends cc.Component {

 
    @property(cc.Node)
    map: cc.Node = null; 
  
    @property(cc.Camera)
    camera: cc.Camera = null;

    @property(cc.Boolean)
    isCameraInMap:boolean = true;
    

    cameraRangeBox:cc.Rect = null;

    enableCameraInMap() {
        this.isCameraInMap = !this.isCameraInMap;
    }

    onLoad () {
        //将色角放入地图
        let p = this.map.convertToNodeSpaceAR(this.node.convertToWorldSpaceAR(cc.v2(0,0)));
        this.node.parent = this.map; 
        this.node.position = cc.v3(p.x,p.y);
        //初始化摄像机边界
        let p1 = this.camera.node.parent.convertToNodeSpaceAR(this.map.convertToWorldSpaceAR(cc.v2(0, 0)));
        let p2 = this.camera.node.parent.convertToNodeSpaceAR(this.map.convertToWorldSpaceAR(cc.v2(this.map.width, this.map.height)));
        let center = cc.v2(cc.winSize.width / 2, cc.winSize.height / 2);
        this.cameraRangeBox = cc.rect(
            p1.x + center.x,
            p1.y + center.y,
            p2.x - center.x,
            p2.y - center.y
        ); 
        //获取地图图层
        this._updateCameraPosition();
    }

    _updateCameraPosition() {
        let p = this.node.convertToWorldSpaceAR(cc.v2(0, 0));
        p = this.camera.node.parent.convertToNodeSpaceAR(p);

        if (this.isCameraInMap)  {
            if (p.x < this.cameraRangeBox.x) {
                p.x = this.cameraRangeBox.x;
            } else if (p.x > this.cameraRangeBox.width) {
                p.x = this.cameraRangeBox.width;
            } 
            if (p.y < this.cameraRangeBox.y) {
                p.y = this.cameraRangeBox.y;
            } else if (p.y > this.cameraRangeBox.height) {
                p.y = this.cameraRangeBox.height;
            }
        } 
        this.camera.node.position = cc.v3(p.x,p.y);
    }

     
    update(){
        this._updateCameraPosition(); 
    }

    
}
